import { BattleRole } from "../role/BattleRole";
import { ITriggerResult } from "./const/ITriggerResult";
import { TriggerBase } from "./TriggerBase";

/**
 * 技能触发事件管理器
 */
export class TriggerMgr {

    private triggerEvents: {};

    constructor() {
        this.triggerEvents = {};
    }

    registerTrigger(trigger: any) {
        if (!this.triggerEvents[trigger.triggerType]) {
            this.triggerEvents[trigger.triggerType] = []
        }
        this.triggerEvents[trigger.triggerType].push(trigger)
    }

    unregisterTrigger(trigger) {
        let list = this.triggerEvents[trigger.triggerType];
        if (list) {
            const index = list.indexOf(trigger);
            if (index != -1) {
                list.splice(index, 1);
            }
        }
    }

    trigger(eventType, args?: { caster: BattleRole, target: BattleRole, results: ITriggerResult[] }) {
        let triggers: TriggerBase[] = this.triggerEvents[eventType];
        if (triggers) {
            for (let i = 0; i < triggers.length; i++) {
                let t = triggers[i];
                t.executeActions(args)
                if (t.isFinish()) {
                    triggers.splice(i, 1);
                    i--;
                }
            }
        }
    }
}
